import web

class Player:
  TURN = 0
  WAIT_TURN = 1
  WIN = 2
  LOSE = 3
  GUESS = 4
  NOT_STARTED = 5
  
  @classmethod
  def create(cls, game, word):
    p = web.insert('players',
                   word = word,
                   game = game,
                   comments = "",
                   alphabet_state_1 = 0,
                   alphabet_state_2 = 0,
                   game_state = Player.NOT_STARTED)
    return cls(p)

  @classmethod
  def participants(cls, game):
    players = web.select('players', where = 'game = $game', order = 'id', vars = locals())
    result = []
    for p in players:
      result.append(cls(p.id))
    return result

  def __init__(self, id):
    players = web.select('players', where = 'id = $id', vars = locals())
    for p in players:
      self.data_id = int(p.id)
      self.data_state = int(p.game_state)
      self.data_state_1 = int(p.alphabet_state_1)
      self.data_state_2 = int(p.alphabet_state_2)
      self.data_word = p.word
      self.data_game = int(p.game)
  def game(self):
    return self.data_game
  def id(self):
    return self.data_id
  def state(self):
    return self.data_state
  def state_1(self):
    return self.data_state_1
  def state_2(self):
    return self.data_state_2
  def word(self):
    return self.data_word
  def update_state(self, state):
    web.update('players',
               where = 'id = $id',
               game_state = state,
               vars = {'id': self.id()})
  def set_turn(self):
    pass
  def set_wait_turn(self):
    players = Player.participants(self.game())
    if self.state() == Player.WAIT_TURN:
      return
    found = False
    self.update_state(Player.WAIT_TURN)
    for p in players:
      if found:
        p.update_state(Player.TURN)
        break
      if p.id() == self.id():
        found = True
    else:
      # current player is the last one in the list
      assert found
      players[0].update_state(Player.TURN)
  def set_vote(self):
    pass
  def set_wait_vote(self):
    pass
  